home *** CD-ROM | disk | FTP | other *** search
Wrap
Public Class DataSetForm Inherits System.Windows.Forms.Form #Region " Windows Form Designer generated code " Public Sub New() MyBase.New() 'This call is required by the Windows Form Designer. InitializeComponent() 'Add any initialization after the InitializeComponent() call End Sub 'Form overrides dispose to clean up the component list. Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) If disposing Then If Not (components Is Nothing) Then components.Dispose() End If End If MyBase.Dispose(disposing) End Sub Friend WithEvents btnCreateTable As System.Windows.Forms.Button Friend WithEvents DataGrid1 As System.Windows.Forms.DataGrid Friend WithEvents btnUppercase As System.Windows.Forms.Button Friend WithEvents btnSelect As System.Windows.Forms.Button Friend WithEvents btnDataView As System.Windows.Forms.Button Friend WithEvents btnRelations As System.Windows.Forms.Button Friend WithEvents DataGrid2 As System.Windows.Forms.DataGrid Friend WithEvents btnConstraints As System.Windows.Forms.Button Friend WithEvents btnSaveXml As System.Windows.Forms.Button Friend WithEvents btnEvents As System.Windows.Forms.Button 'Required by the Windows Form Designer Private components As System.ComponentModel.Container 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent() Me.btnRelations = New System.Windows.Forms.Button() Me.btnSelect = New System.Windows.Forms.Button() Me.btnCreateTable = New System.Windows.Forms.Button() Me.DataGrid2 = New System.Windows.Forms.DataGrid() Me.DataGrid1 = New System.Windows.Forms.DataGrid() Me.btnConstraints = New System.Windows.Forms.Button() Me.btnUppercase = New System.Windows.Forms.Button() Me.btnDataView = New System.Windows.Forms.Button() Me.btnSaveXml = New System.Windows.Forms.Button() Me.btnEvents = New System.Windows.Forms.Button() CType(Me.DataGrid2, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.DataGrid1, System.ComponentModel.ISupportInitialize).BeginInit() Me.SuspendLayout() ' 'btnRelations ' Me.btnRelations.Location = New System.Drawing.Point(16, 256) Me.btnRelations.Name = "btnRelations" Me.btnRelations.Size = New System.Drawing.Size(112, 40) Me.btnRelations.TabIndex = 0 Me.btnRelations.Text = "Create a Relation" ' 'btnSelect ' Me.btnSelect.Location = New System.Drawing.Point(16, 160) Me.btnSelect.Name = "btnSelect" Me.btnSelect.Size = New System.Drawing.Size(112, 40) Me.btnSelect.TabIndex = 0 Me.btnSelect.Text = "Select method" ' 'btnCreateTable ' Me.btnCreateTable.Location = New System.Drawing.Point(16, 16) Me.btnCreateTable.Name = "btnCreateTable" Me.btnCreateTable.Size = New System.Drawing.Size(112, 40) Me.btnCreateTable.TabIndex = 0 Me.btnCreateTable.Text = "Create DataTables" ' 'DataGrid2 ' Me.DataGrid2.AlternatingBackColor = System.Drawing.Color.LightGray Me.DataGrid2.Anchor = (((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _ Or System.Windows.Forms.AnchorStyles.Left) _ Or System.Windows.Forms.AnchorStyles.Right) Me.DataGrid2.BackColor = System.Drawing.Color.DarkGray Me.DataGrid2.CaptionBackColor = System.Drawing.Color.White Me.DataGrid2.CaptionFont = New System.Drawing.Font("Verdana", 10!) Me.DataGrid2.CaptionForeColor = System.Drawing.Color.Navy Me.DataGrid2.DataMember = "" Me.DataGrid2.ForeColor = System.Drawing.Color.Black Me.DataGrid2.GridLineColor = System.Drawing.Color.Black Me.DataGrid2.GridLineStyle = System.Windows.Forms.DataGridLineStyle.None Me.DataGrid2.HeaderBackColor = System.Drawing.Color.Silver Me.DataGrid2.HeaderForeColor = System.Drawing.Color.Black Me.DataGrid2.LinkColor = System.Drawing.Color.Navy Me.DataGrid2.Location = New System.Drawing.Point(144, 224) Me.DataGrid2.Name = "DataGrid2" Me.DataGrid2.ParentRowsBackColor = System.Drawing.Color.White Me.DataGrid2.ParentRowsForeColor = System.Drawing.Color.Black Me.DataGrid2.SelectionBackColor = System.Drawing.Color.Navy Me.DataGrid2.SelectionForeColor = System.Drawing.Color.White Me.DataGrid2.Size = New System.Drawing.Size(488, 160) Me.DataGrid2.TabIndex = 2 ' 'DataGrid1 ' Me.DataGrid1.AlternatingBackColor = System.Drawing.Color.LightGray Me.DataGrid1.Anchor = (((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _ Or System.Windows.Forms.AnchorStyles.Left) _ Or System.Windows.Forms.AnchorStyles.Right) Me.DataGrid1.BackColor = System.Drawing.Color.DarkGray Me.DataGrid1.CaptionBackColor = System.Drawing.Color.White Me.DataGrid1.CaptionFont = New System.Drawing.Font("Verdana", 10!) Me.DataGrid1.CaptionForeColor = System.Drawing.Color.Navy Me.DataGrid1.DataMember = "" Me.DataGrid1.ForeColor = System.Drawing.Color.Black Me.DataGrid1.GridLineColor = System.Drawing.Color.Black Me.DataGrid1.GridLineStyle = System.Windows.Forms.DataGridLineStyle.None Me.DataGrid1.HeaderBackColor = System.Drawing.Color.Silver Me.DataGrid1.HeaderForeColor = System.Drawing.Color.Black Me.DataGrid1.LinkColor = System.Drawing.Color.Navy Me.DataGrid1.Location = New System.Drawing.Point(144, 16) Me.DataGrid1.Name = "DataGrid1" Me.DataGrid1.ParentRowsBackColor = System.Drawing.Color.White Me.DataGrid1.ParentRowsForeColor = System.Drawing.Color.Black Me.DataGrid1.SelectionBackColor = System.Drawing.Color.Navy Me.DataGrid1.SelectionForeColor = System.Drawing.Color.White Me.DataGrid1.Size = New System.Drawing.Size(488, 200) Me.DataGrid1.TabIndex = 2 ' 'btnConstraints ' Me.btnConstraints.Location = New System.Drawing.Point(16, 304) Me.btnConstraints.Name = "btnConstraints" Me.btnConstraints.Size = New System.Drawing.Size(112, 40) Me.btnConstraints.TabIndex = 0 Me.btnConstraints.Text = "Add constraints" ' 'btnUppercase ' Me.btnUppercase.Location = New System.Drawing.Point(16, 64) Me.btnUppercase.Name = "btnUppercase" Me.btnUppercase.Size = New System.Drawing.Size(112, 40) Me.btnUppercase.TabIndex = 0 Me.btnUppercase.Text = "Convert to UpperCase" ' 'btnDataView ' Me.btnDataView.Location = New System.Drawing.Point(16, 208) Me.btnDataView.Name = "btnDataView" Me.btnDataView.Size = New System.Drawing.Size(112, 40) Me.btnDataView.TabIndex = 0 Me.btnDataView.Text = "Create a DataView" ' 'btnSaveXml ' Me.btnSaveXml.Location = New System.Drawing.Point(16, 352) Me.btnSaveXml.Name = "btnSaveXml" Me.btnSaveXml.Size = New System.Drawing.Size(112, 40) Me.btnSaveXml.TabIndex = 0 Me.btnSaveXml.Text = "Save as Xml" ' 'btnEvents ' Me.btnEvents.Location = New System.Drawing.Point(16, 112) Me.btnEvents.Name = "btnEvents" Me.btnEvents.Size = New System.Drawing.Size(112, 40) Me.btnEvents.TabIndex = 0 Me.btnEvents.Text = "DataEvents Events" ' 'DataSetForm ' Me.AutoScaleBaseSize = New System.Drawing.Size(7, 17) Me.ClientSize = New System.Drawing.Size(648, 397) Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.btnEvents, Me.btnSaveXml, Me.btnConstraints, Me.DataGrid2, Me.btnRelations, Me.btnDataView, Me.btnSelect, Me.btnUppercase, Me.DataGrid1, Me.btnCreateTable}) Me.Font = New System.Drawing.Font("Microsoft Sans Serif", 11!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.Name = "DataSetForm" Me.Text = "Disconnected DataSet" CType(Me.DataGrid2, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.DataGrid1, System.ComponentModel.ISupportInitialize).EndInit() Me.ResumeLayout(False) End Sub #End Region ' This is at the form level, to be shared among all procedures. Dim ds As New DataSet() Private Sub btnCreateTable_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreateTable.Click ' --- Define the Employees table --- ' Create a table, set its initial capacity and case sensitiveness. Dim dtEmp As New DataTable("Employees") dtEmp.MinimumCapacity = 100 dtEmp.CaseSensitive = False ' Create all columns. ' You can create a DataColumn and then add it to the Columns collection. Dim dcFName As New DataColumn("FirstName", GetType(String)) dtEmp.Columns.Add(dcFName) ' Or you can create an implicit DataColumn with the Columns.Add method. dtEmp.Columns.Add("LastName", GetType(String)) dtEmp.Columns.Add("BirthDate", GetType(Date)) ' When you have to set additional properties, you can use an explicit ' DataColumn object, or you can use a With block. With dtEmp.Columns.Add("HomeAddress", GetType(String)) .MaxLength = 100 End With ' (When you must set only one property you can be even more concise, ' even though the result isn't very readable.) dtEmp.Columns.Add("City", GetType(String)).MaxLength = 20 ' Create a calculated column, by passing setting the Expression ' property or passing it as the 3rd argument to the Add method. dtEmp.Columns.Add("CompleteName", GetType(String), "FirstName + ' ' + LastName") ' Create an ID column. Dim dcEmpId As New DataColumn("EmpId", GetType(Integer)) dcEmpId.AutoIncrement = True ' Make it autoincrement. dcEmpId.AutoIncrementSeed = 1 dcEmpId.AllowDBNull = False ' Default is True. dcEmpId.Unique = True dtEmp.Columns.Add(dcEmpId) ' Add to Columns collection. ' Make it the primary key. Dim pkCols() As DataColumn = {dcEmpId} dtEmp.PrimaryKey = pkCols ' (You can also use a more concise form, as follows:) dtEmp.PrimaryKey = New DataColumn() {dcEmpId} ' This is a foreign key, but we haven't created the other table yet. dtEmp.Columns.Add("DeptId", GetType(Integer)) ' Add the DataTable to the DataSet. ds.Tables.Add(dtEmp) ' Show the result in the DataGrid. DataGrid2.DataSource = dtEmp ' -- fill the Employees table ' Create a new row with same schema. Dim dr As DataRow = dtEmp.NewRow() ' Set all the columns. dr("FirstName") = "Joe" dr("LastName") = "Doe" dr("BirthDate") = #1/15/1955# dr("HomeAddress") = "1234 A Street" dr("City") = "Los Angeles" dr("DeptId") = 1 ' Add to the Rows collection. dtEmp.Rows.Add(dr) dr = dtEmp.NewRow() ' Set all the columns. dr("FirstName") = "Ann" dr("LastName") = "Doe" dr("BirthDate") = #1/15/1955# dr("HomeAddress") = "1234 A Street" dr("City") = "Los Angeles" dr("DeptId") = 1 dtEmp.Rows.InsertAt(dr, 0) ' Read a semicolon-delimited text file into a DataTable. ' IMPORTANT: this works only if you copy the Employees.Dat ' file from the main project's directory to the BIN subdirectory ' Open the file, read its contents. Dim sr As New System.IO.StreamReader("employees.dat") Dim fileText As String = sr.ReadToEnd sr.Close() ' This regular expression defines a row of elements, and assigns a name ' to each group (that is, a field in the text row). Dim re As New System.Text.RegularExpressions.Regex("""(?<fname>[^""]+)"";""(?<lname>[^""]+)"";(?<bdate>[^;]+);""(?<addr>[^""]+)"";""(?<city>[^""]+)""") Dim ma As System.Text.RegularExpressions.Match dtEmp.BeginLoadData() For Each ma In re.Matches(fileText) ' A new line has been found, so add a row to the table. ' Create an array of values and add it in one operation Dim values() As Object = {ma.Groups("fname").Value, ma.Groups("lname").Value, _ ma.Groups("bdate").Value, ma.Groups("addr").Value, ma.Groups("city").Value} dtEmp.LoadDataRow(values, True) Next dtEmp.EndLoadData() ' --- create the Department table ' Create the Departments table Dim dtDept As New DataTable("Departments") ' The DeptId file must be unique. With dtDept.Columns.Add("DeptId", GetType(Integer)) .Unique = True End With ' The department Name must be unique as well. With dtDept.Columns.Add("Name", GetType(String)) .MaxLength = 50 .Unique = True End With ' Make dtDept the primary key of the table. dtDept.PrimaryKey = New DataColumn() {dtDept.Columns("DeptId")} ' Add to the DataSet. ds.Tables.Add(dtDept) ' Add a few rows. Dim deptValues() As Object = {1, "Sales"} dtDept.LoadDataRow(deptValues, True) ' You can do the same in just one statement. dtDept.LoadDataRow(New Object() {2, "Tech Support"}, True) dtDept.LoadDataRow(New Object() {3, "Marketing"}, True) ' Ensure that all Employees are associated to a department. Dim i As Integer For i = 0 To dtEmp.Rows.Count - 1 ' Assign a DeptId value in the range 1-3. dtEmp.Rows(i).Item("DeptId") = CInt((i Mod 3) + 1) Next ds.AcceptChanges() ' show result in first grid DataGrid1.DataSource = dtDept End Sub ' convert some fields to uppercase Private Sub btnUppercase_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUppercase.Click ' Get a reference to the Employees table. Dim dtEmp As DataTable = ds.Tables("Employees") Dim dr As DataRow For Each dr In dtEmp.Rows dr("FirstName") = dr("FirstName").ToString.ToUpper dr("LastName") = dr("LastName").ToString.ToUpper Next End Sub Private Sub btnEvents_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEvents.Click ' Demonstrate how to deal with events from Employees table. DataTable = ds.Tables(0) End Sub Dim WithEvents DataTable As DataTable ' All the DataTable event handlers ------- Private Sub DataTable_ColumnChanging(ByVal sender As Object, ByVal e As System.Data.DataColumnChangeEventArgs) Handles DataTable.ColumnChanging Dim dt As DataTable = CType(sender, DataTable) Debug.WriteLine("Changing Column " & e.Column.ColumnName & " to " & e.ProposedValue.ToString) ' Show how you can reject a change in a column If e.Column.ColumnName = "BirthDate" Then If CDate(e.ProposedValue) > Date.Now Then 'Throw New ArgumentException("Invalid birth date value") e.Row.SetColumnError(e.Column.ColumnName, "Invalid birth date value") End If End If End Sub Private Sub DataTable_ColumnChanged(ByVal sender As Object, ByVal e As System.Data.DataColumnChangeEventArgs) Handles DataTable.ColumnChanged Dim dt As DataTable = CType(sender, DataTable) Debug.WriteLine("Changed Column " & e.Column.ColumnName & " to " & e.Row(e.Column.ColumnName).ToString) End Sub Private Sub DataTable_RowChanging(ByVal sender As Object, ByVal e As System.Data.DataRowChangeEventArgs) Handles DataTable.RowChanging Dim dt As DataTable = CType(sender, DataTable) Debug.WriteLine("Changing Row (" & e.Action.ToString & ")") If e.Row("FirstName").ToString = "" And e.Row("LastName").ToString = "" Then 'Throw New ArgumentException("FirstName and LastName can't be empty") e.Row.RowError = "First and last name can't be both null" End If End Sub Private Sub DataTable_RowChanged(ByVal sender As Object, ByVal e As System.Data.DataRowChangeEventArgs) Handles DataTable.RowChanged Dim dt As DataTable = CType(sender, DataTable) Debug.WriteLine("Changed Row (" & e.Action.ToString & ")") End Sub Private Sub DataTable_RowDeleting(ByVal sender As Object, ByVal e As System.Data.DataRowChangeEventArgs) Handles DataTable.RowDeleting Dim dt As DataTable = CType(sender, DataTable) Debug.WriteLine("Deleting Row") End Sub Private Sub DataTable_RowDeleted(ByVal sender As Object, ByVal e As System.Data.DataRowChangeEventArgs) Handles DataTable.RowDeleted Dim dt As DataTable = CType(sender, DataTable) Debug.WriteLine("Deleted Row") End Sub ' demonstrates the DataTable.Select method Private Sub btnSelect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSelect.Click ' Get a reference to the Employees table. Dim dtEmp As DataTable = ds.Tables("Employees") ' Copy only the structure of the Employees table in the new table. Dim newDt As DataTable = dtEmp.Clone() newDt.TableName = "YoungEmployees" ' Select a subset of all employees, sorted on their names. Dim drows() As DataRow = dtEmp.Select("DeptId IN (2,3)", "LastName, FirstName") ' Import the array of DataRows into the new table. Dim dr As DataRow For Each dr In drows newDt.ImportRow(dr) Next ' Now show the new table. DataGrid2.DataSource = newDt End Sub ' demonstrate the DataView object Private Sub btnDataView_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDataView.Click ' Get a reference to the Employees table. Dim dtEmp As DataTable = ds.Tables("Employees") ' Create a dataview on this table. Dim dv As New DataView(dtEmp) ' Set its filter and sort properties. dv.RowFilter = "BirthDate >= #1/1/1960#" dv.Sort = "LastName, FirstName" ' Display the dataview in a non-editable DataGrid. dv.AllowEdit = False DataGrid2.DataSource = dv End Sub Private Sub btnRelations_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRelations.Click ' Get a reference to the Employees and Department tables. Dim dtEmp As DataTable = ds.Tables("Employees") Dim dtDept As DataTable = ds.Tables("Departments") ' Now we can create the relation between the two tables. Dim relDeptEmp As New DataRelation("DeptEmp", dtDept.Columns("DeptId"), dtEmp.Columns("DeptId")) ds.Relations.Add(relDeptEmp) ' Display the names of the employees in the first department. Dim drEmployees() As DataRow = dtDept.Rows(0).GetChildRows("DeptEmp") Dim drEmp As DataRow For Each drEmp In drEmployees Debug.WriteLine(drEmp("CompleteName")) Next ' Display the number of employees in each department. Dim dr As DataRow For Each dr In dtDept.Rows Debug.WriteLine(dr("Name").ToString & ", " & _ dr.GetChildRows("DeptEmp").Length.ToString) Next ' This statement returns the name of the department in the first employee. Dim drDepartment As DataRow = dtEmp.Rows(0).GetParentRow("DeptEmp") ' Add a calculated column to the Departments table ' that returns the number of employees for each department dtDept.Columns.Add("EmployeesCount", GetType(Integer), "Count(Child(DeptEmp).EmpID)") ' Add a new Bossid column to the Departments table, and fill it with the ' ID of the first 3 employees. dtDept.Columns.Add("BossId", GetType(Integer)) Dim i As Integer For i = 0 To dtDept.Rows.Count - 1 dtDept.Rows(i)("BossId") = dtEmp.Rows(i)("EmpId") Next dtDept.AcceptChanges() ' Create another relation between the Departments and Employees table. ds.Relations.Add("DeptBoss", dtEmp.Columns("EmpId"), dtDept.Columns("BossId")) ' Add a calcualted column to the Departments table that returns the boss's name. dtDept.Columns.Add("BossName", GetType(String), "Parent(DeptBoss).CompleteName") DataGrid1.DataSource = dtDept End Sub ' create constraints Private Sub btnConstraints_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConstraints.Click ' Get a reference to the Employees and Department tables. Dim dtEmp As DataTable = ds.Tables("Employees") Dim dtDept As DataTable = ds.Tables("Departments") ' Add a unique constraint on the (LastName, FirstName) column combination. ' Prepare the array of involved DataColumn objects. Dim cols() As DataColumn = {dtEmp.Columns("LastName"), _ dtEmp.Columns("FirstName")} ' Create the UniqueConstraint object. Dim uc As New UniqueConstraint("UniqueName", cols) ' Add it to the table's Constraints collection. dtEmp.Constraints.Add(uc) ' Attempt to create duplicate names. Try ' Add a new record that contains duplicated values in (LastName, FirstName) Dim dr As DataRow = dtEmp.NewRow dr("FirstName") = dtEmp.Rows(0)("FirstName") dr("LastName") = dtEmp.Rows(0)("LastName") dr("DeptId") = 1 dtEmp.Rows.Add(dr) Catch ex As Exception MessageBox.Show(ex.Message, "Unique constraint violation", MessageBoxButtons.OK, MessageBoxIcon.Error) End Try ' Create a foreign key constraint If Not (ds.Relations("DeptEmp") Is Nothing) Then MessageBox.Show("You can't add a constraint after a relatin on the same columns") Exit Sub End If Dim fkrelDeptEmp As New ForeignKeyConstraint("FKDeptEmp", dtDept.Columns("DeptId"), dtEmp.Columns("DeptId")) dtEmp.Constraints.Add(fkrelDeptEmp) fkrelDeptEmp.DeleteRule = Rule.SetNull fkrelDeptEmp.UpdateRule = Rule.Cascade fkrelDeptEmp.AcceptRejectRule = AcceptRejectRule.None End Sub ' save the DataSet to XML Private Sub btnSaveXml_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSaveXml.Click 'ds.Relations("DeptEmp").Nested = True With ds.Tables("Employees") .Namespace = "www.vb2themax.com" .Prefix = "emp" End With ds.WriteXml("c:\dataset.xml") End Sub End Class